<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.sys_states" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['bus:platform:add']" type="primary" plain icon="el-icon-plus" class="add"  @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['bus:platform:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button v-hasPermi="['bus:platform:remove']" type="danger" plain icon="el-icon-delete" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['bus:platform:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="platformList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="名称" align="center" prop="title" />
      <el-table-column label="分类" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bus_health_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="图片" align="center" prop="imgUrl">
        <template slot-scope="scope">
          <img :src="'/api' + scope.row.imgUrl" alt="" class="img" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_states" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['bus:platform:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['bus:platform:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改健康管理平台对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="980px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" inline label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl">
          <el-upload class="upload-demo" ref="upload" :action="uploadUrl" :before-upload="handleBeforeUpload"
            :on-success="handleUploadSuccess" :on-remove="handleRemove" :headers="headers" :before-remove="beforeRemove"
            :limit="1" :file-list="fileList" :on-exceed="handleExceed">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="分类" prop="delFlag">
        <el-select v-model="form.type" placeholder="请选择分类">
          <el-option v-for="dict in dict.type.bus_health_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" clearable>
            <el-option v-for="dict in dict.type.sys_states" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频地址" prop="videoUrl">
          <!-- <el-input v-model="form.videoUrl" type="textarea" placeholder="请输入内容" /> -->
          <el-upload class="upload-demo" :action="uploadUrl" :before-upload="handleBeforeUploadVideo"
            :on-success="handleUploadSuccessVideo" :on-remove="handleRemoveVideo" :headers="headers"
            :before-remove="beforeRemove" :limit="1" :file-list="videoList"
            accept="video/mp4,video/x-msvideo,video/quicktime">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传mp4文件，且不超过200MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="富文本内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <!--        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlatform,
  getPlatform,
  delPlatform,
  addPlatform,
  updatePlatform,
} from "@/api/bus/platform";
import { getToken } from "@/utils/auth";
import { listData } from "@/api/system/dict/data";
export default {
  name: "Platform",
  dicts: ["sys_states","bus_health_type"],
  data() {
    return {
      videoList: [],
      fileList: [],
      uploadUrl:
        process.env.VUE_APP_BASE_API + "/common/uploadPc/healthPlatform", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 健康管理平台表格数据
      platformList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // type: 0,
        title: "",
        status: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  async created() {
    this.getList();
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      );
    },
    handleRemove(file) {
      this.form.imgUrl = "";
    },
    handleRemoveVideo() {
      this.form.videoUrl = "";
    },
   
    handleType() { },
    /** 查询健康管理平台列表 */
    getList() {
      this.loading = true;
      listPlatform(this.queryParams).then((response) => {
        console.log(response.data.records);
        this.platformList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        title: null,
        imgUrl: null,
        videoUrl: null,
        orderNum: null,
        status: null,
        content: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.videoList = [];
      this.fileList = [];
      this.resetForm("form");
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`图片格式错误!`);
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 < 500;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 500 KB!`);
          return false;
        }
      }
      return true;
    },
    handleBeforeUploadVideo(file) {
      const isVideo =
        file.type === "video/mp4" ||
        file.type === "video/x-msvideo" ||
        file.type === "video/quicktime";
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isVideo) {
        this.$message.error("上传视频只能是 MP4, AVI, MOV 格式!");
      }
      if (!isLt200M) {
        this.$message.error("上传视频大小不能超过 200MB!");
      }
      return isVideo && isLt200M;
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadSuccessVideo(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.videoUrl = res.fileName;
      } else {
        this.$message.error("图片上传失败");
      }
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.imgUrl = res.fileName;
        // this.$refs.upload.clearFiles();
      } else {
        this.$message.error("图片上传失败");
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加健康管理平台";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      // getPlatform(id).then((response) => {
      this.form = JSON.parse(JSON.stringify(row));
      this.form.status = ''+row.status
      this.form.type = "" + row.type;
      this.open = true;
      console.log("1111", this.fileList);
      if (row.imgUrl) {
        this.fileList = [
          {
            name: row.imgUrl.split("/").pop(),
            url: row.imgUrl,
          },
        ];
      }
      if (row.videoUrl) {
        this.videoList = [
          {
            name: row.videoUrl.split("/").pop(),
            url: row.videoUrl,
          },
        ];
      }

      this.title = "修改健康管理平台";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updatePlatform(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatform(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除健康管理平台编号为"' + ids + '"的数据项？')
        .then(function () {
          return delPlatform(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "bus/platform/export",
        {
          ...this.queryParams,
        },
        `platform_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.img {
  width: 38px;
  height: 38px;
}

.statusBox {
  width: 100%;
  display: flex;
  justify-content: center;
}

.open {
  width: 52px;
  height: 32px;
  background: #e3f9e9;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #2ba471;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #2ba471;
}

.close {
  width: 52px;
  height: 32px;
  background: #d8d8d8;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #767676;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #767676;
}
</style>
